package com.cj.ctyl.controller;

import com.cj.ctyl.entity.SysUsers;
import com.cj.ctyl.framework.core.Result;
import com.cj.ctyl.framework.utils.ServletUtils;
import com.cj.ctyl.service.SysUserService;
import com.google.code.kaptcha.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

/**
 * @Author: Alex
 * @Description: 登录
 * @Date: 2021/8/14
 */
@Controller
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * 跳转登录页
     */
    @RequestMapping("/login")
    public String login(String msg, ModelMap mmap) {
        mmap.put("msg", msg);
        return "/login";
    }

    /**
     * 登录
     */
    @RequestMapping("/doLogin")
    public @ResponseBody
    Result doLogin(String username, String password, String vercode, String remember) {
        HttpSession session = ServletUtils.getSession();
        SysUsers sysUser = sysUserService.login(username, password);
        if (sysUser == null) {
            return Result.warn("账号或密码错误!");
        }

        //验证码验证
        String attribute = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        if (!attribute.toLowerCase().equals(vercode.toLowerCase())) {
            return Result.warn("验证码错误!");
        }

        session.setAttribute("SYSUSER", sysUser);
        return Result.success("登录成功");
    }


    /**
     * 退出登录
     */
    @RequestMapping("/logout")
    public String logout(Long id) {
        HttpSession session = ServletUtils.getSession();
        session.removeAttribute("SYSUSER");
        return "redirect:/login";
    }


}
